using Unity.Collections;
using UnityEngine;

namespace Gameplay.PVE
{
    public struct AStarMapData
    {
        public NativeArray<bool> gridBlock;

        public int mapW;

        public int mapH;

        public Vector3 offset;

        public Quaternion reverseDirection;

        public Quaternion direction;
        
        public Vector2 gridSize;
        
        /// <summary>
        /// 3d坐标 -> 格子坐标
        /// </summary>
        /// <param name="position"></param>
        /// <param name="autoSelectNear"></param>
        /// <returns></returns>
        public Vector2Int GetIndexByPosition(Vector3 position,bool autoSelectNear = false)
        {
            position = reverseDirection * (position - offset);
            int x = (int) (Mathf.Round(position.x / gridSize.x  + mapW / 2f));
            int y = (int) (Mathf.Round(position.z / gridSize.y + mapH / 2f));
            if (x < 0 || y < 0)
            {
                if (autoSelectNear)
                {
                    x = x < 0 ? 0 : x;
                    y = y < 0 ? 0 : y;
                }
                else
                {
                    return Vector2Int.zero;
                }
                
            }
            if (x >= mapW)
            {
                x = mapW - 1;
            }

            if (y >= mapH)
            {
                y = mapH - 1;
            }
            return new Vector2Int(x,y);
        }

        public bool IsBlock(int x, int y)
        {
            var index = GetIndexByVector2(x,y);
            return gridBlock[index];
        }
        
        public bool IsBlock(Vector2Int pos)
        {
            return IsBlock(pos.x, pos.y);
        }

        public int GetIndexByVector2(Vector2Int v2)
        {
            return GetIndexByVector2(v2.x, v2.y);
        }
        
        public int GetIndexByVector2(int x,int y)
        {
            return y * mapW + x;
        }

        public void GetVector2ByIndex(int index,out int x, out int y)
        {
            y = index / mapW;
            x = index % mapW;
        }

        public Vector2Int GetVector2ByIndex(int index)
        {
            GetVector2ByIndex(index,out var x, out var y);
            return new Vector2Int(x,y);
        }
    }
}